import "../sass/shopbag.scss";

import { NavBar } from "react-vant";
import {
    SwipeCell,
    Flex,
    Button,
    Image,
    Typography,
    Stepper,
    Checkbox,
    SubmitBar,
    Toast,
} from "react-vant";

import axios from "axios";

import { useEffect, useState } from "react";

import { useNavigate } from "react-router-dom";

import { useDispatch } from "react-redux";

import { changeCount } from "../store/store";
import imag from "../images/shopbag_bg.png";
function Shopbag() {
    let dispatch = useDispatch();

    let navigate = useNavigate();

    //购物袋数据
    let [shopbagData, setShopbagData] = useState([]);

    //全选状态
    let [isAllSelect, setIsAllSelect] = useState(false);

    //商品总价
    let [total, setTotal] = useState(0);

    //获取购物袋数据
    let getShopbagData = () => {
        axios({
            method: "get",
            url: "/findAllShopcart",
        })
            .then((res) => {
                if (res.data.code === 5000) {
                    res.data.result.forEach((item) => {
                        item.isCheck = false;
                    });
                    setShopbagData(res.data.result);
                    console.log(res.data.result);
                }
            })
            .catch((err) => {});
    };

    let shanchu = (item, count) => {
        let sid = item.sid;
        console.log(count);
        axios({
            method: "post",
            url: "/deleteShopcart",
            data: {
                sids: JSON.stringify([sid]),
            },
        })
            .then((res) => {
                console.log(res);
                getShopbagData();
                axios({
                    method: "post",
                    url: "/modifyShopcartCount",
                    data: {
                        sid,
                        count,
                    },
                })
                    .then((res) => {
                        getShopbagData();
                        if (res.data.code === 700) {
                            return navigate("/login");
                        }
                        if (res.data.code === 6000) {
                            //item.count = count;

                            // shopbagData.splice(index, 1);

                            setShopbagData([
                                ...shopbagData,
                            ]);
                            //获取购物袋总数量
                            let totalCount = 0;
                            console.log(shopbagData);
                            shopbagData.forEach((item) => {
                                totalCount += item.count;
                                console.log(totalCount);
                            });

                            dispatch(
                                changeCount(totalCount)
                            );
                            sum();
                        }
                    })
                    .catch((err) => {});
            })
            .catch((err) => {});
    };
    //修改数量
    let updateCount = (item, value) => {
        axios({
            method: "post",
            url: "/modifyShopcartCount",
            data: {
                sid: item.sid,
                count: value,
            },
        })
            .then((res) => {
                if (res.data.code === 700) {
                    return navigate("/login");
                }

                if (res.data.code === 6000) {
                    item.count = value;
                    setShopbagData([...shopbagData]);

                    //获取购物袋总数量
                    let totalCount = 0;
                    shopbagData.forEach((item) => {
                        totalCount += item.count;
                    });

                    dispatch(changeCount(totalCount));

                    sum();
                }
            })
            .catch((err) => {});
    };

    //全选
    let allSelect = (status) => {
        //
        shopbagData.forEach((item) => {
            item.isCheck = status;
        });
        setIsAllSelect(status);
        setShopbagData([...shopbagData]);

        sum();
    };

    //单选
    let oneSelect = (item, status) => {
        //
        item.isCheck = status;

        setShopbagData([...shopbagData]);

        sum();

        for (let i = 0; i < shopbagData.length; i++) {
            if (!shopbagData[i].isCheck) {
                setIsAllSelect(false);
                return;
            }
        }

        setIsAllSelect(true);
    };

    //计算总价
    let sum = () => {
        let totalMoney = 0;
        shopbagData.forEach((item) => {
            if (item.isCheck) {
                totalMoney += item.price * item.count * 100;
            }
        });

        setTotal(totalMoney);
    };

    //提交订单
    let commitOrder = () => {
        //获取勾选的商品sid
        let sids = [];
        shopbagData.forEach((item) => {
            if (item.isCheck) {
                sids.push(item.sid);
            }
        });

        if (sids.length === 0) {
            Toast({
                message: "请选择购买的商品",
            });
        } else {
            navigate("/pay", { state: { sids } });
        }
    };

    useEffect(() => {
        getShopbagData();
    }, []);

    return (
        <div className="shopbag">
            <NavBar
                title="购物袋"
                leftArrow=""
                rightText="编辑"
            />
            <div>
                <img className="image-gou" src={imag} />
            </div>
            {shopbagData.map((item, index) => {
                return (
                    <div key={index}>
                        <SwipeCell
                            rightAction={
                                <Button
                                    style={{
                                        height: "100%",
                                    }}
                                    square
                                    type="danger"
                                    onClick={() =>
                                        shanchu(
                                            item,
                                            item.count
                                        )
                                    }
                                >
                                    删除
                                </Button>
                            }
                        >
                            <Flex
                                className="demo-product-card"
                                align="stretch"
                            >
                                <div className="check-div">
                                    <Checkbox
                                        checked={
                                            item.isCheck
                                        }
                                        onChange={(
                                            status
                                        ) => {
                                            oneSelect(
                                                item,
                                                status
                                            );
                                        }}
                                        checkedColor="#e4393c"
                                    ></Checkbox>
                                </div>
                                <Image
                                    src={item.small_img}
                                    className="demo-product-card__img"
                                />
                                <Flex
                                    direction="column"
                                    justify="between"
                                    className="demo-product-card__content"
                                >
                                    <div>
                                        <div className="p-title">
                                            {item.name}
                                        </div>
                                        <div>
                                            <Typography.Text type="secondary">
                                                {
                                                    item.enname
                                                }
                                            </Typography.Text>
                                        </div>
                                        <div>
                                            <Typography.Text type="secondary">
                                                {item.rule}
                                            </Typography.Text>
                                        </div>
                                    </div>
                                    <Flex
                                        justify="between"
                                        align="center"
                                    >
                                        <Typography.Text
                                            strong
                                            size="lg"
                                            type="danger"
                                        >
                                            ¥{item.price}
                                        </Typography.Text>
                                        <div>
                                            <Stepper
                                                value={
                                                    item.count
                                                }
                                                onChange={(
                                                    value
                                                ) => {
                                                    updateCount(
                                                        item,
                                                        value
                                                    );
                                                }}
                                                theme="round"
                                                buttonSize="22"
                                                disableInput
                                                min={1}
                                            />
                                        </div>
                                    </Flex>
                                </Flex>
                            </Flex>
                        </SwipeCell>
                    </div>
                );
            })}

            <div>
                <SubmitBar
                    price={total}
                    buttonText="提交订单"
                    onSubmit={() => {
                        commitOrder();
                    }}
                >
                    <Checkbox
                        checkedColor="#e4393c"
                        checked={isAllSelect}
                        onChange={(status) => {
                            allSelect(status);
                        }}
                    >
                        全选
                    </Checkbox>
                </SubmitBar>
            </div>
        </div>
    );
}

export default Shopbag;
